package com.ant.xmla.datacrawling.service.impl;

import cn.hutool.core.date.DateUtil;

import com.ant.xmla.datacrawling.dao.AudioBookDao;
import com.ant.xmla.datacrawling.dao.AudioBookSectionDao;
import com.ant.xmla.datacrawling.entity.AudioBook;
import com.ant.xmla.datacrawling.entity.AudioBookSection;
import com.ant.xmla.datacrawling.service.DownAudioBookService;
import com.ant.xmla.datacrawling.utils.cache.RedisUtil;
import com.ant.xmla.datacrawling.utils.fileUtli.FileReadWriteUtil;
import com.ant.xmla.datacrawling.utils.http.HttpClientUtils;
import com.ant.xmla.datacrawling.utils.pageUtil.PageDevice;
import com.ant.xmla.datacrawling.utils.result.ResultUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.ant.xmla.datacrawling.utils.http.HttpClientUtils.*;


@Service
public class DownAudioBookImpl implements DownAudioBookService {

    private static ResultUtils result = new ResultUtils();

    //获取初始化时间毫秒值
    private static Long initTime  =  System.currentTimeMillis();

    @Resource
    private AudioBookDao audioBookDao;

    @Resource
    private AudioBookSectionDao audioBookSectionDao;

    /**
     * @Description:下载书籍信息
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/5 20:06
     * @Param:  []
     * @return: com.reptile.ant.xmla.Utils.Result.ResultUtils
     * */
    @Override
    public ResultUtils downAudioBookLiterature() {
        //创建实体类
        AudioBook audioBook = new AudioBook();
        //获取章节信息数据
        try {
            //更改:使用多线程进行下载 TODO
            //保存时没有保存到track_id 接口没有取到后期通过查询数据库进行更新 TODO 暂定
            //遍历map获取数据
            Map<Integer, List<String>> bookUrlT  = HttpClientUtils.getBookUrlT();

            Integer j = 0;
            for (Integer key:bookUrlT.keySet()){
                System.out.println("key= "+ key + " and value= " + bookUrlT.get(key));
                audioBook.setAlbumId(key);
                List<String> list = bookUrlT.get(key);
                for (int i = 0; i < list.size(); i++) {
                    audioBook.setAudioBookName(list.get(0));
                    audioBook.setAudioBookUrl(list.get(1));
                    audioBook.setCreateTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                    audioBook.setUpdateTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                    audioBookDao.save(audioBook);
                }
                j++;
            }

            result.setCode("200");
            result.setMessage("保存成功");
            result.setResult("返回结果:"+audioBook+"下载了"+j+"条");
            result.setResultCode(1);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("500");
            result.setMessage("保存失败");
            result.setResult("返回结果:"+e.getMessage());
            result.setResultCode(-1);
            return result;
        }
    }

    /**
     * @Description:下载章节信息
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/6 0:52
     * @Param:  []
     * @return: com.reptile.ant.xmla.Utils.Result.ResultUtils
     * */
    @Override
    public ResultUtils downAudioBookSection() {
        AudioBookSection audioBookSection = new AudioBookSection();
        try{
            Map<Integer, List<String>> bookUrlT  = HttpClientUtils.getBookUrlT();
            Integer j =0;
            for (Integer key :bookUrlT.keySet()){
                Map<Integer, List<String>> chapterInfo = getChapterInfo(key, 1);
                for (Integer chapterInfoKey :chapterInfo.keySet()){
                    System.out.println("key= "+ chapterInfoKey + " and value= " + chapterInfo.get(chapterInfoKey).toString());
                    audioBookSection.setTrackId(chapterInfoKey);
                    List<String> list = chapterInfo.get(chapterInfoKey);
                    for (int i = 0; i < list.size(); i++) {
                        audioBookSection.setTrackName(list.get(0));
                        audioBookSection.setSrc(list.get(1));
                        audioBookSection.setUpdateTime(list.get(2));
                        audioBookSection.setTrackUrl(list.get(3));
                        audioBookSection.setAlbumId(key);
                        audioBookSectionDao.save(audioBookSection);
                        j++;
                    }
                }
            }
            result.setCode("200");
            result.setMessage("保存成功");
            result.setResult("返回结果:"+audioBookSection+"下载了"+j+"条");
            result.setResultCode(1);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("500");
            result.setMessage("保存失败");
            result.setResult("返回结果:"+e.getMessage());
            result.setResultCode(-1);
            return result;
        }
    }

    /**
     * @Description:下载单本书搜索进行下载  todo
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/13 14:52
     * @Param:  []
     * @return: com.ant.xmla.datacrawling.Utils.Result.ResultUtils
     * */
    @Override
    public Integer downAudioBookOne(String param) {
        return HttpClientUtils.inquire(param);
    }

    /**
     * @Description:单个书籍下载
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/9/19 20:11
     * @Param:  [albumId]
     * @return: com.ant.xmla.datacrawling.utils.result.ResultUtils
     * */
    @Override
    public ResultUtils downAudioBookPage(Integer albumId) throws Exception {

        int corePoolSize = 4;
        int maximumPoolSize = 10;
        long keepAliveTime = 600;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        executor.prestartAllCoreThreads(); // 预启动所有核心线程
        executor.execute(()->{
            downAudio(albumId);
        });

        List<Object> nameKey = RedisUtil.getAllKey("name*");
        List<Object> urlKey = RedisUtil.getAllKey("tackId*");
        for (int i = 0; i < nameKey.size(); i++) {
            String name =(String) nameKey.get(i);
            String url = (String) urlKey.get(i);
            String fileName = FileReadWriteUtil.createFile(name);
            FileReadWriteUtil.downloadSource(url,fileName);
        }
        long endTime = System.currentTimeMillis();
        //关闭线程池
        executor.shutdown();
        while (true) {
            if (executor.isTerminated()) {
                result.setResult("多线程下载结束");
                break;
            }
            Thread.sleep(200);
        }
        result.setCode("200");
        result.setMessage("下载完成,一共耗时"+(endTime-initTime)+"毫秒");
        result.setResultCode(1);
        return result;
    }

    /**
     * @Description:下载vip书籍
     * @Author:中国蚂蚁技术有限公司
     * @Date: 2020/10/4 19:14
     * @Param:  [albumId]
     * @return: void
     * */
    private static void downAudio(Integer albumId){
        PageDevice pageInfo = getPageInfo(albumId);
        Integer pageTotal = pageInfo.getPageTotal();
        for (int i = 1; i <= pageTotal; i++) {
            Map<Integer, List<String>> chapterInfo = getChapterInfo(albumId, i);
            for (Integer chapterInfoKey : chapterInfo.keySet()) {
                System.out.println("key= " + chapterInfoKey+" and Value="+chapterInfo.get(chapterInfoKey).toString());
                String name = chapterInfo.get(chapterInfoKey).get(0);
              // String fileName = createFile(RedisUtil.getValue(name));
                String url = HttpClientUtils.vipAudioUrl(chapterInfoKey.toString());
                RedisUtil.setValue("tackId:"+chapterInfoKey,url,1800);
                RedisUtil.setValue("name:"+name,name,1800);
            }
        }
    }
}
